﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SysCommon
{
    public static class EAN
    {
        /// <summary>
        /// 获取EAN
        /// </summary>
        /// <param name="s">传入12位数字</param>
        /// <returns>EAN编码</returns>
        public static string GetEAN13(string s)
        {
            int checkcode_input = -1;//输入的校验码
            if (!Regex.IsMatch(s, @"^\d{12}$"))
            {
                if (!Regex.IsMatch(s, @"^\d{13}$"))
                {
                    return "存在不允许的字符！";
                }
                else
                {
                    checkcode_input = int.Parse(s[12].ToString());
                    s = s.Substring(0, 12);
                }
            }
            int sum_even = 0;//偶数位之和
            int sum_odd = 0;//奇数位之和 
            for (int i = 0; i < 12; i++)
            {
                if (i % 2 == 0)
                {
                    sum_odd += int.Parse(s[i].ToString());
                }
                else
                {
                    sum_even += int.Parse(s[i].ToString());
                }
            }
            int checkcode = (10 - (sum_even * 3 + sum_odd) % 10) % 10;//校验码 
            if (checkcode_input > 0 && checkcode_input != checkcode)
            {
                return "输入的校验码错误！";
            }
            s += checkcode;//变成13位
            return s;
        }

        public static string GetUPC(string s)
        {
            return null;
        }
    }
}
